window.onload = function () {
  const finalVideo1 = document.getElementById("finalVideo1");
  const finalVideo2 = document.getElementById("finalVideo2");
  let recorder1, recorder2;

  const canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d"),
    image = new Image(),
    video = document.getElementById("video");

  const canvas2 = document.getElementById("canvas2"),
    context2 = canvas2.getContext("2d"),
    image2 = new Image(),
    video2 = document.getElementById("video2");

  // 将canvas转成视频
  function canvas2video(canvas, finalVideo, recorder) {
    const stream = canvas.captureStream();
    recorder = new MediaRecorder(stream, { mimeType: "video/webm" });
    const data = [];
    recorder.ondataavailable = function (event) {
      if (event.data && event.data.size) {
        data.push(event.data);
      }
    };
    recorder.onstop = () => {
      const url = URL.createObjectURL(new Blob(data, { type: "video/webm" }));

      finalVideo.style.display = "inline-block";
      finalVideo.src = url;
    };
    return recorder;
  }

  recorder1 = canvas2video(canvas, finalVideo1, recorder1);
  recorder2 = canvas2video(canvas2, finalVideo2, recorder2);

  function animate(ctx, video, img) {
    if (!video.end) {
      ctx.drawImage(video, 0, 0, 300, 300);
      window.requestAnimationFrame(function () {
        animate(ctx, video, img);
      });
      ctx.drawImage(img, 10, 10, 100, 120);
    }
  }
  function canplaythrough(video, recorder, context, image) {
    video.oncanplaythrough = function (e) {
      video.play();
      recorder.start();
      setTimeout(() => {
        recorder.stop();
      }, 6000);
      window.requestAnimationFrame(function () {
        animate(context, video, image);
      });
    };
  }

  // 视频1
  image.src = "./imgs/4.jpg";
  image.onload = function (e) {
    context.drawImage(image, 10, 10, 100, 120);
  };
  canplaythrough(video, recorder1, context, image);

  // 视频2
  image2.src = "./imgs/7.jpeg";
  image2.onload = function (e) {
    context2.drawImage(image, 10, 10, 100, 120);
  };
  canplaythrough(video2, recorder2, context2, image2);
};
